import api from '~api/index'
import util from '~src/lib/util'
export default {
  state: {
    save: {},
    logslist: {
      data: [],
      page: 1,
      id:'-1'
    },
    payInfo:{},
    list: {
      data: [],
      page: 1,
      id:'-1'
    }
  },
  mutations: {
    ['setRecharge'] (state, data) {
      state.save = data
    },
    ['setpayInfo'] (state, data) {
      state.payInfo = data
    },
    ['appendRecharge'] (state, data) {
      var total = parseInt(state.c_list.total)
      state.c_list.data.splice(0,0,data)
      total += 1
      state.c_list.total = total
    },
    ['setBalanceLogs'] (state, data, page) {
      if (page === 1) {
        data.data = [].concat(data.data)
        if (data.data.length === 0){
          data.data = []
        }
      } else {
        data.data = state.logslist.data.concat(data.data)
      }
      state.logslist = data
    }
  },
  actions: {
    async ['getRechargeInfo'] ({commit}, config) {
      const { data: { data, code } } = await api.post('/v1/memberBalanceInfo',
        {openid: util.localItem.get('openid'), card_id: config.id})
      if (data && code === '200') {
        commit('setRecharge', data)
      }
    },
    async ['getBalanceLogs'] ({commit}, config) {
      const { data: { data, code } } = await api.post('/v1/balanceLogs',
        {openid: util.localItem.get('openid'), card_id: config.id,page: config.page, page_size: 12})
      if (data && code === '200') {
        commit('setBalanceLogs', {data: data.log_list?data.log_list:[],total:data.total, page: config.page, id: config.id})
        config.callback && config.callback()
      }else{
        config.stopCallback && config.stopCallback()
      }
    },
    async ['addRecharge'] ({commit}, config) {
      console.log(config)
      const { data: { data, code } } = await api.post('/v1/recharge',
        {
          openid: util.localItem.get('openid'),
          card_id: config.id,
          option_id: config.option_id,
          recharge_money: config.recharge_money
        })
      if (data && code === '200') {
        commit('TOAST_SHOW', {autoClose: false, toast: true, loading: true})
        commit('setpayInfo',data)
      } else {
        commit('TOAST_SHOW', {content: msg, msg: true})
      }
    }
  },
  getters: {
    ['getRechargeInfo'] (state) {
      return state.save
    },
    ['getBalanceLogs'] (state) {
      return state.logslist
    },
    ['getPayInfo'] (state) {
      return state.payInfo
    },
    ['addRecharge'] (state) {
      return state.list
    }
  }
}
